import random
import re

from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from plone.app.layout.viewlets.common import ViewletBase

from zope.component import getMultiAdapter
from Products.CMFCore.utils import getToolByName
from zope.app.component.hooks import getSite

from AccessControl import getSecurityManager

class clear(ViewletBase):
    render = ViewPageTemplateFile('templates/clear.pt')
    
class menuTop(ViewletBase):
    """Viewlet menu.top"""
    render = ViewPageTemplateFile('templates/menuTop.pt')

    def update(self):
        context_state = getMultiAdapter((self.context,self.request),
                                            name=u'plone_context_state')
        actions = context_state.actions()
        self.menu = actions.get('menu_top',None)

    def query(self,itemid,*subitemid):
        miUtils = utils(self.context)
        catalog = miUtils.catalog
        portal = miUtils.portal
        portal = portal.getId()
        path = '/'+ portal + '/' + itemid + '/' + '/'.join(subitemid)
        if len(subitemid)>0:
            path = path
        else:
            path = path[0:-1]
        result = catalog.searchResults(path={'query':path,'depth':1},portal_type=('Folder','Pagina2','Document','Tramite','Descentralizada'))
        return result

    def isAnon(self):
        """retorna el usuario anonymo"""
        plone_tools = getMultiAdapter((self.context, self.request), name=u'plone_tools')
        members = plone_tools.membership()
        anonymous = members.isAnonymousUser()
        return anonymous

class logoViewlet(ViewletBase):
    """logo viewlet"""
    render = ViewPageTemplateFile('templates/logo.pt')
    def update(self):
        super(logoViewlet, self).update()

        portal = self.portal_state.portal()
        logoName = portal.restrictedTraverse('base_properties').logoName
        self.logo_tag = portal.restrictedTraverse(logoName).tag()

        self.portal_title = self.portal_state.portal_title()
        miUtils = utils(self.context)
        catalog = miUtils.catalog
        portal = miUtils.portal
        portal = portal.getId()
        path = path = '/'+portal+'/logo'
        self.result = catalog.searchResults(path={'query':path,'depth':1},portal_type='Image',Title='logo.png')


class menuSlide (ViewletBase):
    """Viewlet menu.slide"""
    render = ViewPageTemplateFile('templates/slide.pt')
    def pics(self):
        miUtils = utils(self.context)
        catalog = miUtils.catalog
        portal = miUtils.portal
        portal = portal.getId()
        path = '/'+portal+'/slide'
        result = catalog.searchResults(path={'query':path,'depth':1},portal_type=('Image'))
        return result

class personalBar(ViewletBase):
    """Viewlet personal_bar"""
    render =  ViewPageTemplateFile('templates/personal.pt')
    def update(self):
        super(personalBar,self).update()

        context_state = getMultiAdapter((self.context,self.request),
                                        name=u'plone_context_state')
        tools = getMultiAdapter((self.context,self.request),
                                name=u'plone_tools')
        sm = getSecurityManager()
        self.user_actions = context_state.actions().get('user',None)

        plone_utils = getToolByName(self.context,'plone_utils')
        self.getIconFor = plone_utils.getIconFor

        self.anonymous = self.portal_state.anonymous()

        if not self.anonymous:
            member = self.portal_state.member()
            userid = member.getId()

            if sm.checkPermission('Portlets: Manage own portlets', self.context):
                self.homelink_url = self.navigation_root_url + '/dashboard'
            else:
                self.homelink_url = self.navigation_root_url + \
                '/personalize_form'

            member_info = tools.membership().getMemberInfo(member.getId())
            # member_info is None if there's no Plone user object, as when
            # using OpenID.
            if member_info:
                fullname = member_info.get('fullname','')
            else:
                fullname = None
            if fullname:
                self.user_name = fullname
            else:
                self.user_name = userid

class actions(ViewletBase):
    """viewlet de site_actions"""
    render = ViewPageTemplateFile('templates/actions.pt')
    def update(self):
      context_state = getMultiAdapter((self.context, self.request),
                                        name=u'plone_context_state')
      self.site_actions = context_state.actions().get('site_actions', None)


class search(ViewletBase):
    """Viewlet search box """
    render = ViewPageTemplateFile('templates/search.pt')
    def update(self):
        super(search,self).update()

        context_state = getMultiAdapter((self.context, self.request),
                                            name=u'plone_context_state')
        props = getToolByName(self.context,'portal_properties')
        livesearch = props.site_properties.getProperty('enable_livesearch',False)
        if livesearch:
            self.search_input_id = "searchGadget"
        else:
            self.search_input_id = ""

        folder = context_state.folder()
        self.folder_path = '/'.join(folder.getPhysicalPath())


class menuMultimedia(ViewletBase):
    """Viewlet menu.multimedia inside portal footer"""
    render =  ViewPageTemplateFile('templates/food.pt')
    def gallerys(self):
        miUtils = utils(self.context)
        catalog = miUtils.catalog
        portal = miUtils.portal
        portal = portal.getId()
        path = '/'+portal+'/galeria-1'
        result = catalog.searchResults(path={'query':path,'depth':1},portal_type='Gallery',
                                       sort_on='Date',sort_order='descending')
        if len(result)>0:
            tam = (len(result))-1
            self.rand = random.randint(0,tam)
        return result

    def videos(self):
        """Retorna los videos del portal"""
        miUtils = utils(self.context)
        catalog = miUtils.catalog
        portal = miUtils.portal
        portal = portal.getId()
        path = '/'+portal+'/videos'
        result = catalog.searchResults(path={'query':path,'depth':1},portal_type=('RTInternalVideo','RTRemoteVideo'),
                                     sort_on='Date',sort_order='descending')
        if len(result)>0:
            tam = (len(result))-1
            self.rand = random.randint(0,tam)
        return result
    
    def imgRemote(self,url):
        """Retorna la imagen thumb del
        video youtube"""

        videoId = re.match('http://.+/.+=(\w{11})(.+)*',url)
        imageremote = 'http://img.youtube.com/vi/' + videoId.group(1) + '/default.jpg'
        return imageremote

class menuBanners(ViewletBase):
    render = ViewPageTemplateFile('templates/banners.pt')

class ploneFooter(ViewletBase):
    """Viewlet plone.footer """
    render =  ViewPageTemplateFile('templates/footer.pt')
    def footer(self):
        miutils = utils(self.context)
        return miutils.portalUrl

class ploneColophon(ViewletBase):
    """Viewlet plone.colophon """
    render =  ViewPageTemplateFile('templates/colophon.pt')
    def colophonContent(self):
        miUtils = utils(self.context)
        catalog = miUtils.catalog
        portal = miUtils.portal
        portal = portal.getId()
        pathSurvey = '/'+portal+'/encuestas'
        self.resultSurveys = catalog.searchResults(path={'query':pathSurvey,'depth':1},portal_type='PlonePopoll',sort_on='Date')

        pathBlog = '/'+portal
        self.resultBlogs = catalog.searchResults(path={'query':pathBlog},portal_type='BlogEntry',sort_on='Date')

        pathEvent = '/'+portal+'/eventos'
        self.resultEvents = catalog.searchResults(path={'query':pathEvent},portal_type='Event',sort_on='Date')

        return miUtils.portalUrl
    
class utils:
    """
    clase que contiene utiles como portal_catalog, portal root, etc
    """
    def __init__(self,context):
        self.context = context
        self.catalog = getToolByName(self.context,'portal_catalog')
        self.portal = getSite()
        self.portalUrl = self.portal.absolute_url()